package ydn.edu.hqu.cst.myexperiment_6_server;

import androidx.appcompat.app.AppCompatActivity;


import android.os.Bundle;
import android.os.Message;
import java.net.*;
import java.io.*;
import java.util.*;
import android.os.Handler;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {
    @BindView(R.id.server_content)
    TextView server_content;
    Handler handler=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch(msg.what){
                    case 0x1234:
                        server_content.setText(server_content.getText().toString()+"\n"+msg.getData().getString("new_content"));
                }
            }
        };
        new Thread(new MyServer(handler)).start();
    }
}
class MyServer implements Runnable {
    //定义保存所有Socket的ArrayList
    //public static ArrayList<Socket> socketList = new ArrayList<Socket>();
    public static ArrayList<Socket> socketList=null;
    Handler handler;

    public MyServer(Handler handler) {
        this.handler = handler;
        socketList = new ArrayList<>();
    }

    @Override
    public void run() {
        try {
            ServerSocket ss = new ServerSocket(10000);
            while (true) {
                //此行代码会阻塞，将一直等待别人的连接
                Socket s = ss.accept();
                socketList.add(s);
                //每当客户端连接后启动一条ServerThread线程为该客户端服务
                new Thread(new ServerThread(s,handler)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class ServerThread implements Runnable {
    // 定义当前线程所处理的Socket
    Socket s = null;
    // 该线程所处理的Socket所对应的输入流
    BufferedReader br = null;
    Handler handler = null;
    public ServerThread(Socket s, Handler handler) throws IOException {
        this.s = s;
        this.handler=handler;
        // 初始化该Socket对应的输入流
        br = new BufferedReader(new InputStreamReader(s.getInputStream(),"utf-8"));
    }
    @Override
    public void run() {
        String content = null;
        // 采用循环不断从Socket中读取客户端发送过来的数据
        while ((content = readFromClient()) != null) {
            // 遍历socketList中的每个Socket，
            // 将读到的内容向每个Socket发送一次
            Message msg = new Message();
            msg.what = 0x1234;
            Bundle bundle = new Bundle();
            bundle.putString("new_content", content);
            msg.setData(bundle);
            handler.sendMessage(msg);
            for (Iterator<Socket> it = MyServer.socketList.iterator(); it.hasNext(); ) {
                Socket outSk = it.next();
                try {
                    OutputStream os = outSk.getOutputStream();
                    os.write((content + "\n").getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                    it.remove();
                }
            }
        }
    }
    // 定义读取客户端数据的方法
    private String readFromClient() {
        try {
            return br.readLine();
        }
        // 如果捕捉到异常，表明该Socket对应的客户端已经关闭
        catch (IOException e) {
            // 删除该Socket。
            e.printStackTrace();
            MyServer.socketList.remove(s);
        }
        return null;
    }
}
